<template>
  <div>
    <!-- 好友审批信息展示 -->
    <el-card class="friend-approval">
      <h2>好友申请</h2>
      <!-- 加载提示 -->
      <el-skeleton v-if="isApprovalLoading" :rows="3" animated />
      <!-- 错误提示 -->
      <el-alert
        v-else-if="approvalErrorMessage"
        :title="approvalErrorMessage"
        type="error"
        show-icon
        @close="fetchFriendRequests"
      />
      <!-- 好友申请列表 -->
      <el-empty v-else-if="friendRequests.length === 0" description="暂无好友申请" />
      <ul v-else class="request-list">
        <li v-for="request in friendRequests" :key="request.userId" class="request-item">
          <el-row :gutter="20" align="middle">

            <el-col :span="14">
              <span class="nickname">{{ request.nickName || request.userName }}</span>
              <p class="message">{{ request.message || '请求添加你为好友' }}</p>
            </el-col>
            <el-col :span="6" class="actions">
              <el-button type="success" size="small" @click="approveOrreject(request, 1)">通过</el-button>
              <el-button type="danger" size="small" @click="approveOrreject(request, 2)">拒绝</el-button>
            </el-col>
          </el-row>
        </li>
      </ul>
    </el-card>

    <!-- 好友列表 -->
    <el-card class="friend-list">
      <h2>好友列表</h2>
      <!-- 加载提示 -->
      <el-skeleton v-if="isLoading" :rows="5" animated />
      <!-- 错误提示 -->
      <el-alert
        v-else-if="errorMessage"
        :title="errorMessage"
        type="error"
        show-icon
        @close="fetchFriendList"
      />
      <!-- 好友列表 -->
      <el-empty v-else-if="paginatedFriends.length === 0" description="暂无好友" />
      <ul v-else class="friend-list-content">
        <li v-for="friend in paginatedFriends" :key="friend.userId" class="friend-item">
          <el-row :gutter="20" align="middle">

            <el-col :span="14">
              <span class="nickname">{{ friend.nickName || friend.userName }}</span>
            </el-col>
            <el-col :span="6" class="actions">
              <el-button type="primary" size="small" @click="startChat(friend)">私聊</el-button>
              <el-button type="danger" size="small" @click="remove(friend)">删除</el-button>
            </el-col>
          </el-row>
        </li>
      </ul>
      <!-- 分页组件 -->
      <el-pagination
        v-if="totalPages > 1"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="friends.length"
        layout="prev, pager, next"
        @current-change="changePage"
      />
    </el-card>
  </div>
</template>

<script>
import {
  approveOrrejectFriend,
  getFriendListByMyId,
  removeFriendById,
} from "~/api/friend";
import { handleCampusUrl } from "~/utils/campus";

export default {
  data() {
    return {
      friends: [],
      currentPage: 1,
      pageSize: 10, // 每页显示更多好友
      isLoading: false,
      errorMessage: null,
      paginatedData: [],
      friendRequests: [],
      isApprovalLoading: false,
      approvalErrorMessage: null
    };
  },
  computed: {
    totalPages() {
      if (!this.friends || this.friends.length === 0) {
        return 0;
      }
      return Math.ceil(this.friends.length / this.pageSize);
    },
    paginatedFriends() {
      return this.paginatedData;
    }
  },
  mounted() {
    this.fetchFriendList();
    this.fetchFriendRequests();
  },
  watch: {
    currentPage() {
      this.updatePaginatedData();
    },
    friends() {
      this.updatePaginatedData();
    }
  },
  methods: {
    fetchFriendList() {
      this.isLoading = true;
      this.errorMessage = null;
      try {
        getFriendListByMyId(1).then((response) => {
          this.friends = response.data;
          this.updatePaginatedData();
        });
      } catch (error) {
        console.error('获取好友列表失败:', error);
        this.errorMessage = '获取好友列表失败，请稍后重试';
      } finally {
        this.isLoading = false;
      }
    },
    remove(friend) {
      var userId = friend.userId;
      this.$confirm("确定要删除好友吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        removeFriendById(userId).then(() => {
          this.fetchFriendList();
        });
      });
    },
    startChat(friend) {
      // 设置缓存
      localStorage.removeItem('friend');
      localStorage.setItem('friend', JSON.stringify(friend));
      this.$router.push({ path: '/friend/chat', query: { friendId: friend.userId } });
    },
    changePage(page) {
      this.currentPage = page;
    },
    // 处理头像URL的方法
    handleAvatarUrl(avatar) {
      return handleCampusUrl(avatar);
    },
    updatePaginatedData() {
      if (!this.friends || this.friends.length === 0) {
        this.paginatedData = [];
        return;
      }
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.paginatedData = this.friends.slice(start, end);
    },
    fetchFriendRequests() {
      this.isApprovalLoading = true;
      this.approvalErrorMessage = null;
      try {
        getFriendListByMyId(0).then((response) => {
          this.friendRequests = response.data;
        });
      } catch (error) {
        console.error('获取好友申请列表失败:', error);
        this.approvalErrorMessage = '获取好友申请列表失败，请稍后重试';
      } finally {
        this.isApprovalLoading = false;
      }
    },
    approveOrreject(request, status) {
      this.$confirm("确定要操作好友申请吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        approveOrrejectFriend(request.userId, status).then(() => {
          this.fetchFriendRequests();
          this.fetchFriendList();
        });
      });
    }
  }
};
</script>

<style scoped>
.friend-approval,
.friend-list {
  padding: 20px;
  max-width: 800px; /* 扩大宽度 */
  margin: 0 auto;
}

.request-list,
.friend-list-content {
  list-style: none;
  padding: 0;
}

.request-item,
.friend-item {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.nickname {
  font-size: 16px;
  font-weight: bold;
}

.message,
.status {
  font-size: 14px;
  color: #888;
  margin: 5px 0;
}

.actions {
  text-align: right;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
